<template>
  <div class="ai-assistant" :class="{ 'is-open': isOpen }">
    <div class="assistant-button" @click="toggleAssistant">
      <a-avatar :size="50" class="avatar">
        <icon-robot />
      </a-avatar>
    </div>
    
    <div class="assistant-container">
      <div class="assistant-header">
        <h3>AI 助手</h3>
        <a-space>
          <a-button size="mini" type="text" @click="minimize">
            <icon-minus />
          </a-button>
          <a-button size="mini" type="text" @click="toggleAssistant">
            <icon-close />
          </a-button>
        </a-space>
      </div>
      
      <div class="chat-container" ref="chatContainer">
        <div v-if="messages.length === 0" class="empty-state">
          <p>您好！我是您的AI助手，请问有什么可以帮您？</p>
        </div>
        
        <div v-for="(message, index) in messages" :key="index" :class="['message', message.sender]">
          <div class="message-content">
            {{ message.text }}
          </div>
        </div>
        
        <div v-if="isTyping" class="message ai">
          <div class="typing-indicator">
            <span></span>
            <span></span>
            <span></span>
          </div>
        </div>
      </div>
      
      <div class="input-container">
        <a-textarea
          v-model="userInput"
          placeholder="输入您的问题..."
          :disabled="isTyping"
          @press-enter="sendMessage"
          :auto-size="{ minRows: 1, maxRows: 4 }"
        />
        <a-button 
          type="primary" 
          shape="circle" 
          @click="sendMessage"
          :disabled="!userInput || isTyping"
          class="send-button"
        >
          <template #icon>
            <icon-send />
          </template>
        </a-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import { Avatar, Button, Space, Textarea } from '@arco-design/web-vue'
import { IconRobot, IconSend, IconMinus, IconClose } from '@arco-design/web-vue/es/icon'

interface ChatMessage {
  text: string
  sender: 'user' | 'ai' | 'system'
  timestamp?: string
}

const isOpen = ref(false)
const isTyping = ref(false)
const userInput = ref('')
const messages = ref<ChatMessage[]>([])
const chatContainer = ref<HTMLElement | null>(null)




const scrollToBottom = () => {
  nextTick(() => {
    if (chatContainer.value) {
      chatContainer.value.scrollTop = chatContainer.value.scrollHeight
    }
  })

}
const addMessage = (text: string, sender: 'user' | 'ai' | 'system') => {
  messages.value.push({
    text,
    sender,
    timestamp: new Date().toISOString()
  })
  scrollToBottom()
}


// 初始化欢迎消息
onMounted(() => {
    addMessage('您好！我是您的AI助手，请问有什么可以帮您？', 'ai');
})

const toggleAssistant = () => {
  isOpen.value = !isOpen.value
}

const minimize = () => {
  isOpen.value = false
}



const getAIResponse = async (userMessage: string): Promise<string> => {
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 800 + Math.random() * 700))
    
    const lowerMessage = userMessage.toLowerCase()
    
    if (lowerMessage.includes('你好') || lowerMessage.includes('hello')) {
        return '您好！很高兴为您服务。请问有什么可以帮您？'
    }
    if (lowerMessage.includes('名字') || lowerMessage.includes('谁')) {
        return '我是一个AI助手，专门设计来回答您的问题和提供帮助。'
    }
    if (lowerMessage.includes('时间')) {
        return '当前时间是：' + new Date().toLocaleTimeString()
    }
    if (lowerMessage.includes('天气')) {
        return '抱歉，我目前无法获取实时天气信息。您可以尝试使用专业的天气应用或网站。'
    }
    return '感谢您的消息。我会尽力为您提供帮助，如果您需要更专业的协助，请告诉我更多细节。'
}



const sendMessage = async () => {
  if (!userInput.value.trim() || isTyping.value) return
  
  const userMessage = userInput.value.trim()
  addMessage(userMessage, 'user')
  userInput.value = ''
  
  try {
    isTyping.value = true
    const aiResponse = await getAIResponse(userMessage)
    addMessage(aiResponse, 'ai')
  } catch (error) {
    console.error('获取AI响应失败:', error)
    addMessage('抱歉，我暂时无法响应您的请求，请稍后再试。', 'ai')
  } finally {
    isTyping.value = false
  }
}



// 暴露方法给父组件
defineExpose({
  toggle: toggleAssistant,
  minimize,
  addMessage
})
</script>
<style scoped>
.ai-assistant {
  position: fixed;
  bottom: 30px;
  right: 30px;
  z-index: 1000;
  transition: all 0.3s ease;
}

.assistant-button {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background: #E8F3FF;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.assistant-button:hover {
  transform: scale(1.1);
  background: #D1E9FF;
}

.avatar {
  background: #165DFF;
  color: white;
}

.assistant-container {
  position: absolute;
  bottom: 70px;
  right: 0;
  width: 350px;
  max-height: 500px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
  overflow: hidden;
  transform: translateY(20px);
  opacity: 0;
  visibility: hidden;
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
}

.is-open .assistant-container {
  transform: translateY(0);
  opacity: 1;
  visibility: visible;
}

.assistant-header {
  padding: 12px 16px;
  background: #165DFF;
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.assistant-header h3 {
  margin: 0;
  font-size: 16px;
}

.chat-container {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  background: #f5f5f5;
}

.empty-state {
  text-align: center;
  color: #888;
  padding: 20px 0;
}

.message {
  margin-bottom: 12px;
  display: flex;
}

.message.user {
  justify-content: flex-end;
}

.message-content {
  max-width: 80%;
  padding: 8px 12px;
  border-radius: 12px;
  line-height: 1.5;
  word-break: break-word;
}

.ai .message-content {
  background: white;
  border: 1px solid #e5e5e5;
}

.user .message-content {
  background: #E8F3FF;
}

.typing-indicator {
  display: flex;
  gap: 4px;
  padding: 8px 12px;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  background: #888;
  border-radius: 50%;
  display: inline-block;
  animation: typingAnimation 1.4s infinite ease-in-out;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typingAnimation {
  0%, 60%, 100% { transform: translateY(0); }
  30% { transform: translateY(-4px); }
}

.input-container {
  padding: 12px;
  background: white;
  border-top: 1px solid #e5e5e5;
  display: flex;
  gap: 8px;
}

.send-button {
  flex-shrink: 0;
}

@media (max-width: 768px) {
  .ai-assistant {
    bottom: 20px;
    right: 20px;
  }
  
  .assistant-container {
    width: 300px;
    max-height: 400px;
  }
}
</style>